package com.example.demo.controller;

import cn.hutool.core.io.FileUtil;
import com.example.demo.pojo.Result;
import com.example.demo.service.IUserService;
import jakarta.servlet.ServletOutputStream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import jakarta.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLConnection;
import java.net.URLEncoder;

@RestController
@RequestMapping("/file")

public class FileController {
    private static final String Root_Path = System.getProperty("user.dir") + File.separator + "file";
    @Autowired
    private IUserService userService;
    @PostMapping("/upload")
    public Result upload(MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        //aaa.png
        String mainName = FileUtil.mainName(originalFilename);//aaa
        String extName = FileUtil.extName("png");//png
        if (!FileUtil.exist(Root_Path)) {
            FileUtil.mkdir(Root_Path);//如果当前文件的父级目录不存在创建一个
        }
//        File saveFile = new File(Root_Path + File.separator + originalFilename);
        if (FileUtil.exist(Root_Path + File.separator + originalFilename)) {
            originalFilename = System.currentTimeMillis() + "_" + mainName + "." + extName;
//            saveFile = new File(Root_Path + File.separator + originalFilename);
        }
        File saveFile = new File(Root_Path + File.separator + originalFilename);
        file.transferTo(saveFile);
        String url = "http://localhost:8089" + "/file/download/" + originalFilename;
        return Result.success(url);
    }

    /**
     //     * 获取文件（预览图片）
     //     */

    @GetMapping("/download/{fileName}")
    public void download(@PathVariable String fileName, HttpServletResponse response) throws IOException {
        String filePath = Root_Path + File.separator + fileName;
        if (FileUtil.exist(filePath)) {
            // 设置正确的MIME类型
            String mimeType = URLConnection.guessContentTypeFromName(fileName);
            if (mimeType == null) {
                mimeType = "application/octet-stream"; // 默认值
            }
            response.setContentType(mimeType);

            response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + URLEncoder.encode(fileName, "UTF-8") + "\"");

            byte[] bytes = FileUtil.readBytes(filePath);
            ServletOutputStream outputStream = response.getOutputStream();
            outputStream.write(bytes);
            outputStream.flush();
            outputStream.close();
        } else {
            response.sendError(HttpServletResponse.SC_NOT_FOUND, "File not found");
        }
    }


}
